import React from 'react';
import { Form, Input, FormInstance, Select } from 'antd';

type UserName = '_id' | 'username' | 'password' | 'phone' | 'email' | 'role_id' | 'create_time';
type UserInfo = Record<UserName, string> & { __v: 0 };
type RoleInfo = {
    menus: string[];
    _id: string;
    name: string;
    auth_time: number;
    auth_name: string;
    create_time: number;
}
type Props = {
    addUserRef: React.MutableRefObject<FormInstance | null>;
    roles: RoleInfo[];
    user: UserInfo | null;
};

type FormItemLayout = {
    labelCol: {
        sm: { span: number };
    };
    wrapperCol: {
        sm: { span: number };
    };
};

const formItemLayout: FormItemLayout = {
    labelCol: {
        sm: { span: 4 }
    },
    wrapperCol: {
        sm: { span: 15 }
    }
};

// 添加用户的form组件
const UserForm: React.FC<Props> = ({ addUserRef, roles, user }) => {
    const [form] = Form.useForm();
    addUserRef.current = form;
    return (
        <Form {...formItemLayout} form={form}>
            <Form.Item initialValue={user?.username} label="用户" name="username">
                <Input type="text" placeholder="请输入用户名称" />
            </Form.Item>
            {
                user?._id
                    ? null
                    : (
                        <Form.Item label="密码" name="password">
                            <Input type="text" placeholder="请输入密码" />
                        </Form.Item>
                    )
            }
            <Form.Item initialValue={user?.phone} label="手机" name="phone">
                <Input type="text" placeholder="请输入手机号" />
            </Form.Item>
            <Form.Item initialValue={user?.email} label="邮箱" name="email">
                <Input type="text" placeholder="请输入邮箱" />
            </Form.Item>
            <Form.Item initialValue={user?.role_id} label="角色" name="role_id">
                <Select placeholder="请选择">
                    {
                        roles.map(({ _id, name }) => (
                            <Select.Option key={_id} value={_id}>{name}</Select.Option>
                        ))
                    }
                </Select>
            </Form.Item>
        </Form>
    );
};

export default UserForm;